<template>
	<view id="calendar_container">
		<!-- 日历组件 -->
		<view class="calendar_conpos">
			<uni-calendar class="uni-calendar--hook" :selected="calendarInfo.selected" :showMonth="false" @change="calendarChangeHandle" @monthSwitch="monthSwitch" />
		</view>
		<!-- 选择当天的账单 -->
		<view class="bill_show">
			<view v-if="billData.length === 0" class="no-data">当日账单数据</view>
			<view v-for="(bill, index) in billData" :key="bill.id" class="bill-item" 
			:class="{ 'not_first_bill': index != 0 }">
				<view class="bill-info">
					<!-- 账单左侧 月-日 基本信息 -->
					<view class="bill-info-left">
						<view class="bill-info-left-icon">
							<image :src="baseUrl + bill.iconName" mode="heightFix"></image>
						</view>
						<view class="bill-info-left-content">
							<view class="bill-info-left-content_type">
								{{ bill.typeName }}
							</view>
							<view class="bill-info-left-content-remark">
								{{ bill.remark }}
							</view>
							<view class="bill-info-left-content-time">
								{{ bill.transactionTime }}
							</view>
						</view>
					</view>
					<!-- 账单右侧金额 -->
					<view class="bill-info-right">
						<view class="bill-info-right-mount">
							<!-- 收入和支出不同的样式 -->
							<span v-if="bill.type == 2" class="expend_style">-{{ bill.amount }}</span>
							<span v-else class="income_style">+{{ bill.amount }}</span>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
// 当前显示月份
const currentMonth = ref('2025-02');

// 显示账单数据
let billData = ref([]);
// 文件系统根路径
let baseUrl = uni.$baseUrl + 'category$';

// 日历组件信息
const calendarInfo = ref({
	lunar: true,
	range: true,
	insert: false,
	selected: [] // 初始化空数组
});

onMounted(() => {
	getEveryDayIeOfMonth(getFormattedDate());
	// 获取当前日期的账单
	getDayBillData(getNowDate());
});

// 选择日历日期处理器
// 选择日历日期处理器
const calendarChangeHandle = async (e) => {
    // 对月份和日期补零，确保始终为两位数格式
    const formattedMonth = String(e.month).padStart(2, '0');
    const formattedDate = String(e.date).padStart(2, '0');
    let dateParam = `${e.year}-${formattedMonth}-${formattedDate}`;

    try {
        const res = await uni.$http.get(`/bills/getBillByDate/${dateParam}`);

        if (res.data.code == 0) {
            uni.$showT(res.data.msg);
            return 0;
        }

        // 赋值账单数据
        billData.value = res.data.data;

    } catch {
        uni.$showT('网络异常');
    }
};

// 获取当前年月
function getFormattedDate() {
	const date = new Date();
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0'); // +1 因为月份从0开始
	return `${year}-${month}`;
}

// 获取年月日
function getNowDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // +1 因为月份从0开始
    const day = String(date.getDate()).padStart(2, '0'); // 新增补零操作
    return `${year}-${month}-${day}`;
}

// 根据日期获取当天账单数据
async function getDayBillData(dateParam){
	console.log("获取当天账单：", dateParam);
	const res = await uni.$http.get(`/bills/getBillByDate/${dateParam}`);
	console.log("获取到的账单：", res.data);
	if (res.data.code == 0) {
		uni.$showT(res.data.msg);
		return 0;
	}
	
	// 赋值账单数据
	billData.value = res.data.data;
}

// 月份切换处理器
const monthSwitch = (e) => {
	currentMonth.value = e.year + '-' + e.month.toString().padStart(2, '0');
	console.log("切换月份到：", currentMonth.value);
	getEveryDayIeOfMonth(currentMonth.value);
	// 构造年月日，重新刷新选择当天的所有账单
	let getBillParam = "";
	if(e.month < 10){
		getBillParam = e.year + '-0' + e.month + '-01'
	}else{
		getBillParam = e.year + '-' + e.month + '-01'
	}
	getDayBillData(getBillParam);
};

// 获取月份每日净收支
const getEveryDayIeOfMonth = async (month) => {
	try {
		const res = await uni.$http.get(`/bills/getCalendarDayDataOfMonth/${month}`);
		if (res.data.code === 1) {
			// 转换数据结构并过滤0值
			const formattedData = Object.entries(res.data.data)
				.filter(([_, amount]) => amount !== 0) // 新增过滤逻辑
				.map(([date, amount]) => ({
					date: date,
					info: `${amount >= 0 ? '+' : ''}${amount.toFixed(2)}`,
					extra: {
						color: amount >= 0 ? '#67C23A' : '#F56C6C'
					}
				}));

			calendarInfo.value.selected = formattedData;
		}
		
	} catch (error) {
		uni.showToast({
			title: '数据加载失败',
			icon: 'none'
		});
	}
};
</script>

<style>
/* 自定义日历样式 */
.uni-calendar--hook .calendar-item__info {
	font-size: 12px !important;
	line-height: 16px !important;
}

.bill_show {
	margin-top: 20rpx;
	/* height: 50px; */
	background-color: #fff;
	padding: 20rpx 0px;
}

.no-data {
	text-align: center;
	color: #888;
	padding: 30rpx;
}

.bill-item {
	display: flex;
	flex-direction: column;
	margin-bottom: 10px;
	padding: 10px;
	border-bottom: 1px solid #ccc;
	border-radius: 5px;
	padding-bottom: 20rpx;
}

.bill-info {
	display: flex;
	justify-content: space-between;
	font-size: 15px;
}

.bill-amount {
	font-weight: bold;
}

.bill-type {
	color: #666;
}

.bill-date {
	color: #999;
}

.bill-info-left {
	display: flex;
}

.bill-info-left-icon {
	display: flex;
	justify-content: center;
	align-items: center;
}

.bill-info-left-icon image {
	height: 40px;
}

.bill-info-left-content {
	margin-left: 10rpx;
}

.bill-info-left-content-remark {
	padding: 10rpx 0px;
}

.bill-info-left-content-time,
.bill-info-left-content-remark {
	font-size: 13px;
	color: #626262;
}

.bill-info-right {
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 14px;
	font-weight: 600;
}

.expend_style {
	color: #f10000;
}

.income_style {
	color: #00c300;
}

.not_first_bill {
	/* border-top: solid #d5d5d5 1px; */
}
</style>
